package com.imax.center.websocket;

import com.alibaba.fastjson.JSON;
import com.imax.center.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/webSocket/{userId}")
public class WsEndpoint {

    @Value("${tcp.log.enable}")
    private boolean logEnable;

    //连接用户的sessionMap
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws IOException {
        //如果已存在就删除
        if (sessionMap.containsKey(userId)) {
            Session oldSession = sessionMap.get(userId);
            oldSession.close();
            sessionMap.remove(userId);
        }
        sessionMap.put(userId, session);
        log.info("User {} connected", userId);
        this.sendMessage(session, "连接成功");
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        sessionMap.remove(userId);
        log.info("User {} disconnected", userId);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("userId") String userId) {
        log.info("on message={}", message);
        this.sendMessageToAllUser(message);
    }

    public void sendMessageToAllUser(Object message) {
        if (logEnable) {
            log.info("send message={}", message);
        }
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            this.sendMessage(entry.getValue(), message);
        }
    }

    //发送消息
    private void sendMessage(Session session, Object message) {
        try {
            session.getBasicRemote().sendText(JSON.toJSONString(Result.success(message)));
        } catch (IOException e) {
            log.error("Error sending message", e);
        }
    }

    @OnError
    public void onError(Throwable error) {
        log.error("Error in chat endpoint", error);
    }

}